package com.api.controller;

import cn.hutool.http.HttpException;
import com.api.entity.Sms;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import org.json.JSONException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhaoyu
 * @version 1.0
 * @description: TODO
 * @date 2021/8/5 16:20
 */
@RestController
@RequestMapping("/Sms")
public class SmsController {
    @PostMapping("/SmsCode")
    public Map<Object,Object> sms(@RequestBody String phone){
        Map<Object,Object> map = new HashMap<>();
        //服务器SDK AppID
        int appId = 1400555638;
        //服务器App Key
        String appKey = "";
        //短信正文id
        int templateId = 1065399;
        //短信签名
        String smsSign = "赵宇java分享个人网";
        try{
            String code = createRandom();
            //短信模板参数
            String[] params = {code};
            //腾旭云短信接口
            SmsSingleSender smsSingleSender = new SmsSingleSender(appId,appKey);
            //发送短信
            SmsSingleSenderResult smsSingleSenderResult = smsSingleSender.sendWithParam(
                    "86",
                    phone,
                    templateId,
                    params,
                    smsSign,
                    "",
                    "");
            if (smsSingleSenderResult.errMsg.equals("OK")){
                map.put("start","200");
                map.put("code",code);

            }
        }catch (HTTPException e){
            e.printStackTrace();
        }catch (JSONException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 创建指定数量的随机字符串
     * @return
     */
    public static String createRandom(){
        String retStr = "";
        String strTable = "1234567890";
        int len = strTable.length();
        boolean bDone = true;
        do {
            retStr = "";
            int count = 0;
            for (int i = 0; i < 6; i++) {
                double dblR = Math.random() * len;
                int intR = (int) Math.floor(dblR);
                char c = strTable.charAt(intR);
                if (('0' <= c) && (c <= '9')) {
                    count++;
                }
                retStr += strTable.charAt(intR);
            }
            if (count >= 2) {
            bDone = false;
            }
        } while (bDone);
        return retStr;
    }
}
